package org.sixtynine.stock.dao.impl;

/**
 * @author Thilan
 *
 */

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.sixtynine.stock.Constants;
import org.sixtynine.stock.dao.CustomerUpgradeDao;
import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.CustomerUpgrade;
import org.springframework.stereotype.Repository;

@Repository
public class CustomerUpgradeDaoImpl extends
		AbstractDaoImpl<CustomerUpgrade, Integer> implements CustomerUpgradeDao {

	protected CustomerUpgradeDaoImpl() {
		super(CustomerUpgrade.class);
	}

	@Override
	public void saveCustomerUpgrade(CustomerUpgrade customerUpgrade) {
		saveOrUpdate(customerUpgrade);
	}

	@Override
	public List<CustomerUpgrade> searchCustomerUpgrade(int packageId) {
		return findByCriteria(Restrictions.eq("packg.id", packageId));
	}

	@Override
	public CustomerUpgrade searchCustomerUpgradeFromCustomer(int customerId) {
		if (findByCriteria(Restrictions.eq("user.id", customerId)).size() > 0) {
			return findByCriteria(Restrictions.eq("user.id", customerId))
					.get(0);
		} else {
			return null;
		}

	}

	@Override
	public CustomerUpgrade searchCustomerUpgrade(String orderId) {
		if (findByCriteria(Restrictions.eq("orderId", orderId)).size() > 0) {
			return findByCriteria(Restrictions.eq("orderId", orderId)).get(0);
		} else {
			return null;
		}
	}

	@Override
	public Page<CustomerUpgrade> searchCustomerUpgrade(int packageId,
			Date fromDate, Date toDate, String orderBy, GridPramDTO gridPramDTO) {
		Criteria criteria = getCurrentSession().createCriteria(
				CustomerUpgrade.class);

		criteria.addOrder(Order.desc(getRecordOrder(orderBy)));

		if (packageId > Constants.ERROR) {
			criteria.add(Restrictions.eq("packg.id", packageId));
		}
		if (fromDate != null) {
			criteria.add(Restrictions.ge("upgradeDate", fromDate));
		}

		if (toDate != null) {
			criteria.add(Restrictions.le("upgradeDate", toDate));
		}

		return findByCriteria(criteria, gridPramDTO);
	}

}
